package orm

import (
	"bytes"
	"fmt"
)

type Field struct {
	Id           string `gorm:"column:id"`
	ProjectId    string `gorm:"column:projectId"`
	TableName    string `gorm:"column:tableName"`
	FieldName    string `gorm:"column:fieldName"`
	FieldType    string `gorm:"column:fieldType"`
	IsPrimaryKey string `gorm:"column:isPrimaryKey"`
}

func GetTableNames(projectId interface{}) (tableNames []string) {
	db.Table("tableinfos").Select("tableName").Distinct().Find(&tableNames)
	return tableNames
}

func GetTableFields(projectId string, tableName string) (fields []Field) {
	db.Table("tableinfos").Where("tableName = ? and isPrimaryKey='false'", tableName).Find(&fields)
	return fields
}

func GetTableAllFields(tableName string) (fields []Field) {
	db.Table("tableinfos").Where("tableName = ?", tableName).Find(&fields)
	return fields
}

func GetPrimaryField(projectId string, tableName string) (field Field) {
	db.Table("tableinfos").Where("tableName = ? and isPrimaryKey='true'", tableName).Find(&field)
	return field
}

func GetFeildNames(projectId string, tablename string) (fields []string) {
	db.Table("tableinfos").Select("fieldName").Where("tableName = ?", tablename).Find(&fields)
	return fields
}

func BatchSave(fields []*Field) error {
	var buffer bytes.Buffer
	sql := "insert into `tableinfos` (`id`,`projectId`,`tableName`,`fieldName`,`fieldType`,`isPrimaryKey`) values"
	if _, err := buffer.WriteString(sql); err != nil {
		return err
	}
	for i, e := range fields {
		if i == len(fields)-1 {
			buffer.WriteString(fmt.Sprintf("('%s','%s','%s','%s','%s','%s');", e.Id, e.ProjectId, e.TableName, e.FieldName, e.FieldType, e.IsPrimaryKey))
		} else {
			buffer.WriteString(fmt.Sprintf("('%s','%s','%s','%s','%s','%s'),", e.Id, e.ProjectId, e.TableName, e.FieldName, e.FieldType, e.IsPrimaryKey))
		}
	}
	return db.Exec(buffer.String()).Error
}

func DeleteByProjectId(projectId string) error {
	return db.Exec("delete from tableinfos where projectId=$1", projectId).Error
}
